//
//  UserChooserOrderController.m
//  bestkeep
//
//  Created by windCould on 16/12/20.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "UserChooserOrderController.h"
#import "BKUserUnitRequestAPI.h"
#import "MJExtension.h"
#import "BKUserChatSignalOrderModel.h"
#import "BKUserAskOrderCellTableViewCell.h"
#import "BKMyCommon.h"
#import "BKRefreshGifHeader.h"
#import "BKNewRefreshFooter.h"
#import "PromptTools.h"
#import "BKUserCodeFormat.h"
@interface UserChooserOrderController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)NSMutableArray * storeArr;
@property (nonatomic,strong)NSArray * dataArr;
@property (nonatomic,assign)NSInteger   curpage;
@property (nonatomic,assign)NSInteger   totalPage;
@property (nonatomic,strong) ExceptionView * exceptionView;
@end

@implementation UserChooserOrderController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.navigationItem.title = @"选择要咨询的订单";
    self.storeArr = [NSMutableArray array];
    self.tableView.tableFooterView = [[UIView alloc]init];
    [self loadDataWithStatus:@"" pageSize:10 pageNo:1];
    [self addRefresh];
}

-(void)addRefresh
{
    //BKRefreshGifHeader *headerRefresh = [BKRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    //self.tableView.mj_header = headerRefresh;
    
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(updateMore)];
    footer.stateLabel.textColor = [UIColor lightGrayColor];
    footer.stateLabel.font = [UIFont systemFontOfSize:14];
    footer.arrowView.image = [UIImage imageNamed:@"BKGDPullDown"];
    UIActivityIndicatorView *loadingView = [footer valueForKeyPath:@"loadingView"];
    loadingView.hidesWhenStopped = YES;
    loadingView.color = RGBCOLOR(42,187,155,1);
    [footer addSubview:loadingView];
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.automaticallyHidden = YES;
}

-(void)updateMore
{
    
    if (self.curpage == self.totalPage) {
        
        [self.tableView.mj_footer endRefreshing];
        if ([BKUserCodeFormat isOverWholeScreenWithDataArray:_dataArr rowHeight:78]) {
            
            self.tableView.tableFooterView = [PromptTools getViewWhenDataEndLoading];
            self.tableView.mj_footer = nil;
        } else {
            
            self.tableView.tableFooterView = [[UIView alloc]init];
        }
        
        return ;
    }
    
    NSInteger  pageRequest = self.curpage;
    [self loadMoreDataWithStatus:@"" pageSize:10 pageNo:pageRequest + 1];
}




-(void)refreshData
{
    [self reloadDataWithStatus:@"" pageSize:10 pageNo:1];
}

-(void)setDataArr:(NSArray *)dataArr
{
    _dataArr = dataArr;
    if (self.curpage == self.totalPage) {
        
        [self.tableView.mj_footer endRefreshing];
        if ([BKUserCodeFormat isOverWholeScreenWithDataArray:_dataArr rowHeight:78]) {
            
            self.tableView.tableFooterView = [PromptTools getViewWhenDataEndLoading];
            self.tableView.mj_footer = nil;
        } else {
            
            self.tableView.tableFooterView = [[UIView alloc]init];
        }
    }
    
    [self.tableView reloadData];
}

-(void)setGetOrderInfo:(getSelectedOrderInfo)getOrderInfo
{
    if (getOrderInfo) {
        
        _getOrderInfo = getOrderInfo;
    }

}

#pragma mark =========================NetRequestWork=================================

-(void)loadDataWithStatus:(NSString *)status pageSize:(NSInteger)pageSize pageNo:(NSInteger)pageNo
{
    NSString * pageSizeStr = [NSString stringWithFormat:@"%ld",(long)pageSize];
    NSString * pageNoStr = [NSString stringWithFormat:@"%ld",(long)pageNo];

    NSDictionary * paraDict = @{@"status":status,@"pageno":pageNoStr,@"pagesize":pageSizeStr};
    
    if(self.exceptionView) {
        
        [self.exceptionView dismiss];
        self.exceptionView = nil;
    }
    
    [BKIndicationView showInView:self.view];
    __weak typeof(self) weakSelf = self;
    [BKUserUnitRequestAPI getWantToAskOrderWithParaDict:paraDict resultBlock:^(id obj, NSError *error) {
        [BKIndicationView dismiss];
        
        if (obj) {
            
            NSDictionary * dataDict = obj;
            BOOL success = [[dataDict objectForKey:@"success"] boolValue];
            if (success) {
                
                weakSelf.totalPage = ([[[obj objectForKey:@"data"] objectForKey:@"total"] integerValue] +  [[[obj objectForKey:@"data"] objectForKey:@"pagesize"] integerValue]  - 1) / [[[obj objectForKey:@"data"] objectForKey:@"pagesize"] integerValue];
                weakSelf.curpage = [[[obj objectForKey:@"data"] objectForKey:@"pageno"] integerValue];
                NSArray * dataArr = [BKUserChatAllOrderModel mj_objectArrayWithKeyValuesArray:dataDict[@"data"][@"rows"]];
                weakSelf.dataArr = dataArr;
                weakSelf.storeArr = [NSMutableArray arrayWithArray:dataArr];
                if (weakSelf.dataArr.count == 0) {
                
                    weakSelf.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeEmptyPages];
                    ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:ExceptionCodeTypeEmptyPages handler:^(ExceptionViewAction *action) {
                        
                        [weakSelf loadDataWithStatus:@"" pageSize:10 pageNo:1];
                    }];
                    [self.exceptionView addAction:retryAction];
                    
                    [self.exceptionView showInView:self.view];
                    
                }
            }
        } else {
        
            if(!self.exceptionView && error) {
            
                ExceptionCodeType errorType = ExceptionCodeTypeRequestFailed;
                if (error.code == -1009) {
                    errorType = ExceptionCodeTypeNoNetwork;
                }else if (error.code == -1001){
                    errorType = ExceptionCodeTypeRequestFailed;
                }else if (error.code == 502 || error.code == 404){
                    errorType = ExceptionCodeTypeServerError;
                }else{
                    errorType = ExceptionCodeTypeFailedToLoad;
                }

                weakSelf.exceptionView = [ExceptionView exceptionViewWithType:errorType];
                ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:errorType handler:^(ExceptionViewAction *action) {
                    
                    [weakSelf loadDataWithStatus:@"" pageSize:10 pageNo:1];
                }];
                
                [self.exceptionView addAction:retryAction];
                [self.exceptionView showInView:self.view];
        }
        }
    }];
}

-(void)reloadDataWithStatus:(NSString *)status pageSize:(NSInteger)pageSize pageNo:(NSInteger)pageNo
{
    NSString * pageSizeStr = [NSString stringWithFormat:@"%ld",(long)pageSize];
    NSString * pageNoStr = [NSString stringWithFormat:@"%ld",(long)pageNo];
    NSDictionary * paraDict = @{@"status":status,@"pageno":pageNoStr,@"pagesize":pageSizeStr};
    __weak typeof(self) weakSelf = self;
    
    [BKUserUnitRequestAPI getWantToAskOrderWithParaDict:paraDict resultBlock:^(id obj, NSError *error) {
        [weakSelf.tableView.mj_header endRefreshing];
        if (obj) {
        
            NSDictionary * dataDict = obj;
            BOOL success = [[dataDict objectForKey:@"success"] boolValue];
            if (success) {
                
                weakSelf.totalPage = ([[[obj objectForKey:@"data"] objectForKey:@"total"] integerValue] +  [[[obj objectForKey:@"data"] objectForKey:@"pagesize"] integerValue]  - 1) / [[[obj objectForKey:@"data"] objectForKey:@"pagesize"] integerValue];
                weakSelf.curpage = [[[obj objectForKey:@"data"] objectForKey:@"pageno"] integerValue];
                NSArray * dataArr = [BKUserChatAllOrderModel mj_objectArrayWithKeyValuesArray:dataDict[@"data"][@"rows"]];
                weakSelf.dataArr = dataArr;
                weakSelf.storeArr = [NSMutableArray arrayWithArray:dataArr];
                if ([[[obj objectForKey:@"data"] objectForKey:@"total"] integerValue] == dataArr.count) {
                    
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                    weakSelf.tableView.mj_footer = nil;
                }
                
            } else {
                
                [HUD showErrorMessage:[paraDict objectForKey:@"msg"]];
            }
        } else {
            
            [HUD showErrorMessage:error.localizedDescription];
        }
    }];

}

-(void)loadMoreDataWithStatus:(NSString *)status pageSize:(NSInteger)pageSize pageNo:(NSInteger)pageNo
{
    NSString * pageSizeStr = [NSString stringWithFormat:@"%ld",(long)pageSize];
    NSString * pageNoStr = [NSString stringWithFormat:@"%ld",(long)pageNo];
    NSDictionary * paraDict = @{@"status":status,@"pageno":pageNoStr,@"pagesize":pageSizeStr};
    
    __weak typeof(self) weakSelf = self;
    [BKUserUnitRequestAPI getWantToAskOrderWithParaDict:paraDict resultBlock:^(id obj, NSError *error) {
        
        [weakSelf.tableView.mj_footer  endRefreshing];
        if (obj) {
        
            NSDictionary * dataDict = obj;
            BOOL success = [[dataDict objectForKey:@"success"] boolValue];
            if (success) {
                
                weakSelf.curpage = [[[obj objectForKey:@"data"] objectForKey:@"pageno"] integerValue];
                NSArray * dataArr = [BKUserChatAllOrderModel mj_objectArrayWithKeyValuesArray:dataDict[@"data"][@"rows"]];
                [weakSelf.storeArr addObjectsFromArray:dataArr];
                weakSelf.dataArr = weakSelf.storeArr;
            
            } else {
                
                //[HUD showErrorMessage:[paraDict objectForKey:@"msg"]];
                [BKShowBottomTiPMessageView showMessage:[paraDict objectForKey:@"msg"]];
            }
        } else {
            
            //[HUD showErrorMessage:error.localizedDescription];
            [BKShowBottomTiPMessageView showMessage:error.localizedDescription];
        }
    }];

}


#pragma mark =========================UITableViewDelegate============================

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return self.dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    BKUserChatAllOrderModel * allOrderModel = self.dataArr[section];
    return allOrderModel.item_list.count;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * hView = [[UIView alloc]init];
    hView.backgroundColor = RGBCOLOR(242, 242, 242,1);
    UILabel * OrderNum = [[UILabel alloc]initWithFrame:CGRectMake(hView.frame.origin.x, hView.frame.origin.y + 12, SCREENWIDTH, 30)];
    OrderNum.backgroundColor = [UIColor whiteColor];
    OrderNum.textAlignment = NSTextAlignmentLeft;
    OrderNum.textColor = RGBCOLOR(64, 64, 64,1);
    OrderNum.font = [UIFont systemFontOfSize:13];
     BKUserChatAllOrderModel * allOrderModel = self.dataArr[section];
    OrderNum.text = [NSString stringWithFormat:@"  订单号: %@",allOrderModel.order_no];
    [hView addSubview:OrderNum];
    return hView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 78;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 42;
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 28;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView * ftView = [[UIView alloc]init];
    ftView.backgroundColor = [UIColor whiteColor];
    UILabel * ftLabel = [[UILabel alloc]initWithFrame:CGRectMake(ftView.frame.origin.x, ftView.frame.origin.y, SCREENWIDTH - 10, 30)];
    ftLabel.backgroundColor = [UIColor whiteColor];
    ftLabel.textAlignment = NSTextAlignmentRight;
    ftLabel.textColor = RGBCOLOR(64, 64, 64,1);
    ftLabel.font = [UIFont systemFontOfSize:13];
    BKUserChatAllOrderModel * allOrderModel = self.dataArr[section];
    ftLabel.text =[NSString stringWithFormat:@"共%@件商品 合计:  ¥%.2f",allOrderModel.amount,[allOrderModel.order_amount floatValue]];
    [ftView addSubview:ftLabel];
    return ftView;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BKUserChatAllOrderModel * allModel = self.dataArr[indexPath.section];
    BKUserChatSignalOrderModel * signalModel = allModel.item_list[indexPath.row];
    BKUserAskOrderCellTableViewCell * cell = [BKUserAskOrderCellTableViewCell cellWithTableview:tableView];
    cell.singalOrderModel = signalModel;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BKUserChatAllOrderModel * allModel = self.dataArr[indexPath.section];
    BKUserChatSignalOrderModel * signalModel = allModel.item_list[indexPath.row];
    
    NSDictionary *dic = @{
                          @"order_title":[NSString stringWithFormat:@"订单号:%@",allModel.order_no],
                          @"title":@"dadada",
                          @"price":[NSString stringWithFormat:@"¥ %.2f",[allModel.order_amount floatValue]],
                          @"item_url":@"dadadada",
                          @"type":@"order",
                          @"imageName":@"dadad",
                          @"desc":[NSString stringWithFormat:@"共%@件商品",allModel.amount],
                          @"img_url":signalModel.goods_img
                          };
    
    if (_getOrderInfo) {
        
        _getOrderInfo(dic);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

@end
